package com.szwistar.common.algorithm;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class SHA1 {
	public static byte[] get(byte[] val) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("SHA1");
            md5.update(val);
            return md5.digest();
        } catch (Exception e) {
            return null;
        }
	}

	public static byte[] get(String val) {
		return get(val.getBytes());
	}

	public static byte[] get(InputStream fin) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("SHA1");
            byte[] buf = new byte[1024];
            int len = 0;
            // 循环读取数据并计算
            while((len = fin.read(buf)) > 0) {
                md5.update(buf, 0, len);
            }
            // 计算摘要
            return md5.digest();
        } catch (Exception e) {
            return null;
        }
    }

    public static byte[] get(File file) {
    	FileInputStream in = null;
    	try {
            in = new FileInputStream(file);
            byte[] md5 = get(in);
            in.close(); in = null;
            return md5;
		} catch (Exception e) {
			if(in != null) { try { in.close(); in = null; } catch (Exception e1) {} }
			return null;
		}
    }
}
